/********************************************************************************
 * Project Name		[JavaSE_Fundamentals]
 * File Name     	[EnumSerialization.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package io.serialization;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * jdk 1.5之前的枚举定义, 只有一个常量值<br/>
 * 默认的序列化机制不适于自定义枚举: 即使构造器私有, 序列化机制也能创建新的对象<br/>
 * jdk 1.5的枚举则可以正常序列化<br/>
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class EnumSerialization implements Serializable {

	private static final long serialVersionUID = -7515155225565102211L;

	private final int value;

	// jdk 1.5之前定义的枚举
	public static final EnumSerialization V = new EnumSerialization(1);

	private EnumSerialization(int value) {
		this.value = value;
	}

	public int getValue() {
		return value;
	}

	/**
	 * 错误的序列化方式
	 * 
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static void incorrectSerializationMethod() throws IOException, ClassNotFoundException {
		EnumSerialization v1 = EnumSerialization.V;
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("enum1.ser"));
		out.writeObject(v1);
		out.close();

		ObjectInputStream in = new ObjectInputStream(new FileInputStream("enum1.ser"));
		EnumSerialization v2 = (EnumSerialization) in.readObject();
		in.close();

		if (v1 == v2) {
			System.out.println("Serialization successfully");
		} else {
			System.out.println("serialization unsuccessfully");
		}
	}

	/**
	 * 正确的序列化方式 [单例模式也要使用此种序列化方式]
	 * 
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static void correctSerializationMethod() throws IOException, ClassNotFoundException {
		EnumSerialization v1 = EnumSerialization.V;
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("enum2.ser"));
		out.writeInt(v1.getValue());
		out.close();

		ObjectInputStream in = new ObjectInputStream(new FileInputStream("enum2.ser"));
		int v2 = in.readInt();
		in.close();

		if (v1.value == v2) {
			System.out.println("Serialization successfully");
		} else {
			System.out.println("serialization unsuccessfully");
		}
	}

	public static void main(String[] args) {
		try {
			incorrectSerializationMethod();
			correctSerializationMethod();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
